package com.nicefact.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;

public class KeyListService {
	// private static final AppLogger log =
	// AppLogger.getLogger(KeyListService.class);

	private PersistenceManager persistenceManager;

	public KeyListService(PersistenceManager persistenceManagerFactory) {
		this.persistenceManager = persistenceManagerFactory;
	}

	public PersistenceManager getPersistenceManager() {
		return this.persistenceManager;
	}

	public <E> List<E> getByKeys(Collection<Key> keyList, Class<E> type) {
		PersistenceManager persistenceManager = getPersistenceManager();
		List<E> results = new ArrayList<E>();
		if (keyList == null || keyList.isEmpty())
			return results;
		Query query = persistenceManager.newQuery(type);
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.setFilter(":keyList.contains(key)");
		results.addAll(persistenceManager.detachCopyAll((Collection<E>) query
				.execute(keyList)));
		return results;

	}

	public <E> Collection<E> getByKeys(Collection<Key> keyList, Class<E> type,
			String field) {
		PersistenceManager persistenceManager = getPersistenceManager();
		Collection<E> results = new ArrayList<E>();
		if (keyList == null || keyList.isEmpty())
			return results;
		Query query = persistenceManager.newQuery(type);
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.setFilter(":keyList.contains(" + field + ")");
		results.addAll(persistenceManager.detachCopyAll((Collection<E>) query
				.execute(keyList)));
		return results;

	}

	public Collection<Object> getObjectsByKeys(Collection<Object> keyList,
			Class<?> type) {
		PersistenceManager persistenceManager = getPersistenceManager();
		Collection<Object> results = new ArrayList<Object>();
		if (keyList == null || keyList.isEmpty())
			return results;
		Query query = persistenceManager.newQuery(type);
		query.declareImports("import com.google.appengine.api.datastore.Key");
		query.setFilter(":keyList.contains(key)");
		results.addAll(persistenceManager
				.detachCopyAll((Collection<Object>) query.execute(keyList)));
		return results;

	}
}
